<template>
  <a-drawer
    title="应用管理"
    :closable="false"
    :width="950"
    :visible="visiblePri"
    @close="onClose"
  >
    <div style="width: 100%;display: flex;justify-content: flex-end;margin-bottom: 10px;">
      <a-button type="primary" @click="add">新增</a-button>
    </div>
    <a-table
      :loading="loading"
      :scroll="{ x: 1000 }"
      :columns="columns"
      :data-source="tableData"
      :rowKey="(record) => record.id"
    >
      <template slot="clientTypes" slot-scope="text, record">
        <span v-for="(item, index) in record.clientTypes" :key="index">
          {{newInviteConfig[item]}}
        </span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <div class="editable-row-operations">
          <span>
            <a @click="() => edit(record, 'edit')" style="margin-right: 20px;">编辑</a>
            <a-popconfirm
              title="确定删除吗？"
              ok-text="是"
              cancel-text="否"
              @confirm="confirmDialog(record.id)"
            >
              <a href="#">删除</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
    </a-table>

    <a-modal
      :title="type === 'add' ? '新增' : '编辑'"
      :visible="modalVisible"
      :confirm-loading="confirmLoading"
      @ok="invitationHandleOk"
      :zIndex="1001"
      @cancel="invitationHandleCancel"
    >
      <a-form-model
        :model="form"
        ref="form"
        v-if="modalVisible"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="rules"
      > 
        <a-form-model-item label="应用授权" prop="systemId" class="form-item">
            <a-select
              :getPopupContainer="getPopupContainer"
              v-model="form.systemId"
              style="width: 100%"
              placeholder="请选择子系统"
              :options="inviteApps"
              @change="handleChange"
            ></a-select>
        </a-form-model-item>
        <a-form-model-item label="子系统" prop="clientTypes" class="form-item">
          <a-checkbox-group v-model="form.clientTypes" :options="clientTypesEnum[form.systemId]" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-drawer>
</template>
<script>
import { getClientsList, addNewInvite, editNewInvite, deleteNewInvite } from "@/services/newInvite"
import { commonValidate } from "@/utils/util"
export default {
  name: "selected-draw",
  props: ['visible', 'tableData', 'selectOpenId'],
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 12 },
      confirmLoading: false,
      resourceList: [],
      loading: false,
      cacheData: [],
      editingKey: '',
      modalVisible: false,
      newInviteConfig: {
        1: 'ios',
        2: 'android',
        3: '小程序',
        4: 'web',
        // 5: 'pc',
        99: 'iot'
      },
      rules: {
        systemId: [
          { required: true, message: "请选择系统", trigger: "change" }
        ],
        clientTypes: [
          { required: true, message: "请选择子系统", trigger: "change" }
        ]
      },
      inviteApps: [],
      clientTypesEnum: [],
      columns: [
        {
          title: '子系统名称',
          dataIndex: 'systemName',
          scopedSlots: { customRender: 'systemName' },
          key: 'systemName'
        },
        {
          title: '子系统ID',
          dataIndex: 'systemId',
          scopedSlots: { customRender: 'systemId' },
          key: 'systemId'
        },
        {
          title: '子应用名称',
          dataIndex: 'clientTypes',
          scopedSlots: { customRender: 'clientTypes' },
          key: 'clientTypes'
        },
        {
          title: '操作',
          key: 'operation',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      type: '',
      row: {},
      form: {
        systemId: '',
        clientTypes: []
      }
    };
  },
  computed: {
    visiblePri: {
      get() {
        return this.visible;
      },
      set() {}
    },
    departmentIdPri: {
      get() {
        return this.departmentId;
      },
      set() {}
    }
  },
  watch: {
    visible() {
      // val && this.init()
    }
  },
  methods: {
    async init() {
      this.loading = true;
    },
    getPopupContainer() {
      return document.body
    },
    handleChange() {
      this.form.clientTypes = []
    },
    async edit(row) {
      this.type = 'edit'
      this.modalVisible = true
      this.row = row
      this.clientTypesEnum = {
        [row.systemId]: row.systemClientTypes.split(',').map(i => ({
          value: i,
          label: this.newInviteConfig[i]
        }))
      }
      this.inviteApps = [row].map(item => {
        return {
          ...item,
          value: item.systemId,
          label: item.systemName
        }
      })
      this.form.systemId = row.systemId
      this.form.clientTypes = row.clientTypes.map(i => {
        return i 
      })
      console.log(this.form)
    },
    async confirmDialog(id) {
      this.modalVisible = false
      const res = await deleteNewInvite(id)
      if (res.data.code === 200) {
        this.$emit('updateTable')
        this.$message.success("删除成功");
      } else {
        this.$message.success(res.data.message);
      }
    },
    inviteAppsValidate(r, value) {
      let f = value.every(arr => arr.length === 0)
      if (f) {
        return Promise.reject('请至少选择一个子应用');
      } else {
        return Promise.resolve()
      }
    },
    async getNewInviteList() {
      const appId = window.__POWERED_BY_QIANKUN__
          ? this.$store.state.account.appId
          : process.env.VUE_APP_ID; // 平台id
      const res = await getClientsList({
        appId
      })
      if(res.data.code === 200) {
        this.inviteApps = res.data.data
        this.inviteApps = this.inviteApps.map(item => {
          const clientTypesEnum = item.clientTypes.split(',').filter(i => i !== '5')
          this.clientTypesEnum = {...this.clientTypesEnum, ...{
            [item.systemId]: clientTypesEnum.map(i => ({
              value: i,
              label: this.newInviteConfig[i]
            }))
          }}
          return {
            ...item,
            value: item.systemId,
            label: item.systemName
          }
        })
        console.log(this.clientTypesEnum )
      }
    },
    warning(message) {
      const that = this;
      this.$warning({
        title: "信息提示",
        content: (
          <div style="color:red">
            {message}
          </div>
        ),
        onOk() {
          that.modalVisible = false;
          that.form = {
            systemId: '',
            clientTypes: []
          };
        }
      });
    },
    async invitationHandleOk() {
      const validateResult = await commonValidate(this.$refs.form)
      if (!validateResult) return
      const appId = window.__POWERED_BY_QIANKUN__
          ? this.$store.state.account.appId
          : process.env.VUE_APP_ID; // 平台id
      const { enterpriseId } = this.$store.state.account
      if (this.type === 'add') {
        const res = await addNewInvite({
          openId: this.selectOpenId,
          appId,
          systemId: this.form.systemId,
          enterpriseId,
          clientTypes: this.form.clientTypes.join(',')
        })
        this.modalVisible = false;
        if (res.data.code !== 200) {
          this.warning(res.data.message);
          return;
        }
        this.$refs.form.resetFields();
        this.$emit('updateTable')
        this.$message.success("邀请成功");
        return
      }
      if (this.type === 'edit') {
        const res = await editNewInvite({
          openId: this.selectOpenId,
          appId,
          systemId: this.form.systemId,
          id: this.row.id,
          clientTypes: this.form.clientTypes.join(',')
        })
        this.modalVisible = false;
        if (res.data.code !== 200) {
          this.warning(res.data.message);
          return;
        }
        this.$refs.form.resetFields();
        this.$emit('updateTable')
        this.$message.success("邀请成功");
      }
    },
    invitationHandleCancel() {
      this.modalVisible = false
    },
    async add() {
      this.type = 'add'
      this.modalVisible = true
      this.form = {
        systemId: '',
        clientTypes: []
      }
      this.getNewInviteList()
    },
    onClose() {
      this.$emit('closeDraw')
    },
    onSave() {}
  }
};
</script>
<style lang="less">
.mt30 {
  position: absolute;
  bottom: 20px;
  right: 50px;
}
</style>
